package com.sanley.coronavirus.common.security;

import com.alibaba.fastjson2.JSON;
import com.sanley.coronavirus.common.api.CommonResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: ming
 * @create: 2022-10-14 21:11
 * @program: coronavirus
 */
@Service("authenticationFailHandler")
public class AuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override

    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {

        this.returnJson(response, exception);

    }

    private void returnJson(HttpServletResponse response,

                            AuthenticationException exception) throws IOException {

        response.setStatus(HttpServletResponse.SC_OK);

        response.setCharacterEncoding("UTF-8");

        response.setContentType("application/json");

        response.getWriter().print(JSON.toJSONString(CommonResult.unauthorized("用户名或密码错误")));

    }

}
